<template>
    <TheElDialog
        ref="dialog"
        :title="title"
        :visible.sync="multipleAddVisible"
        minWidth
        v-bind="$attrs"
        v-on="$listeners"
    >
        <div v-loading="isMultipleLoading">
            <div v-if="isAdd">
                <el-button style="width: 100%;margin-bottom: 10px;" type="primary" @click="onPushSelection"
                    >+1 行数据</el-button
                >
            </div>
            <el-table :data="multipleCreateSelection" border style="width: 100%">
                <el-table-column type="index"> </el-table-column>
                <el-table-column prop="name" label="项目名称*">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>项目名称</template>
                    <template v-slot="{row}">
                        <template v-if="isDetail">{{ row.name }}</template>
                        <el-form
                            v-else
                            @submit.native.prevent
                            :key="`form_name_${row.uuid}`"
                            :ref="`form_name_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="name" label="">
                                <el-input
                                    v-model="row.name"
                                    placeholder="请填写项目名称，例如：支出-成本-工资发放"
                                ></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="类型*">
                    <template v-slot:header><span style="color:#f00;padding-right: 4px;">*</span>类型</template>
                    <template v-slot="{row}">
                        <template v-if="isDetail">{{
                            {id: row.type, arr: ITEM_OUT_IN_TYPE, value: 'value', prop: 'label'} | findValue
                        }}</template>
                        <el-form
                            v-else
                            @submit.native.prevent
                            :key="`form_type_${row.uuid}`"
                            :ref="`form_type_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="type" label="">
                                <el-select v-model="row.type" placeholder="请选择" style="width: 100%;">
                                    <el-option
                                        v-for="item in ITEM_OUT_IN_TYPE"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注">
                    <template v-slot="{row}">
                        <el-form
                            @submit.native.prevent
                            :key="`form_remark_${row.uuid}`"
                            :ref="`form_remark_${row.uuid}`"
                            :model="row"
                            :rules="RULES"
                        >
                            <el-form-item prop="remark" label="">
                                <template v-if="isDetail">{{ row.remark }}</template>
                                <el-input
                                    v-else
                                    type="textarea"
                                    rows="1"
                                    :show-word-limit="row.remark ? row.remark && row.remark.length > 150 : false"
                                    :maxlength="200"
                                    v-model="row.remark"
                                    placeholder=""
                                ></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column v-if="!isDetail" align="center" label="操作" :width="50">
                    <template v-slot="{row}">
                        <el-button size="small" @click="onRemoveAddSelection(row)" type="text">
                            移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="isMultipleLoading" @click="multipleAddVisible = false">取 消</el-button>
            <el-button v-if="isDetail" type="primary" plain @click="onClickPrint('dialog')">打 印</el-button>
            <el-button
                v-else
                :disabled="isDetail"
                :loading="isMultipleLoading"
                type="primary"
                @click="onClickMultipleOkCreate(multipleCreateSelection, $refs)"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import {postApisList, putApisList} from '@/api/itemOutIn';
import {v4 as uuidv4} from 'uuid';
import getRules, {formValidates} from '@/views/system/item-out-in/getRules';
import dialogToPrint from '@/utils/dialogToPrint';
import {ITEM_OUT_IN_TYPE} from '@/views/system/item-out-in/constants';
const dataSourceDefault = {
    id: undefined,
    name: '',
    contact: '',
    phone: '',
    address: '',
    outStart: '',
    outEnd: '',
    remark: ''
};
export default {
    name: 'BatchDialog',
    props: {
        type: {type: String, default: 'add'}, // type === "add" 添加, type === "edit" 编辑, type === 'detail' 详情
        title: {type: String, default: '批量添加'},
        visible: {type: Boolean, default: false, required: true},
        multipleSelection: {type: Array, required: false, default: () => []},
        tableData: {type: Array, required: false, default: () => []},
        isLoading: {type: Boolean, default: false, required: true},
        onRemoveUpdateSelection: {type: Function, default: () => () => {}, required: false}
    },
    data() {
        return {
            ITEM_OUT_IN_TYPE,
            RULES: getRules(),
            multipleCreateSelection: [
                {...dataSourceDefault, uuid: uuidv4()},
                {...dataSourceDefault, uuid: uuidv4()}
            ]
        };
    },
    computed: {
        multipleAddVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        },
        isMultipleLoading: {
            get() {
                return this.isLoading;
            },
            set(val) {
                this.$emit('update:isLoading', val);
            }
        },
        multipleValueSelection: {
            get() {
                return this.multipleValueSelection || [];
            },
            set(val) {
                this.$emit('update:multipleValueSelection', val);
            }
        },
        isEdit() {
            return this.type === 'edit';
        },
        isDetail() {
            return this.type === 'detail';
        },
        isAdd() {
            return this.type === 'add';
        }
    },
    watch: {
        multipleAddVisible: {
            handler(val) {
                if (val && this.isAdd) {
                    this.multipleCreateSelection = [
                        {...dataSourceDefault, uuid: uuidv4()},
                        {...dataSourceDefault, uuid: uuidv4()}
                    ];
                }
            },
            deep: true,
            immediate: true
        },
        multipleSelection: {
            handler(val) {
                if (this.isEdit || this.isDetail) {
                    this.multipleCreateSelection = val || [];
                }
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        onRemoveAddSelection(row) {
            if (this.isEdit) {
                this.onRemoveUpdateSelection(row);
                return;
            }
            this.multipleCreateSelection = this.multipleCreateSelection.filter(({uuid}) => uuid !== row.uuid);
        },
        onPushSelection() {
            this.multipleCreateSelection.push({...dataSourceDefault, uuid: uuidv4()});
        },
        // 批量添加
        async onClickMultipleOkCreate(multipleCreateSelection, refs) {
            if (this.isEdit) {
                this.onClickMultipleOkUpdate(multipleCreateSelection, refs);
                return;
            }
            if (multipleCreateSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量添加失败'});
                return;
            }
            try {
                await formValidates.call(this, multipleCreateSelection, refs);

                this.isMultipleLoading = true;
                postApisList(multipleCreateSelection)
                    .then(res => {
                        this.multipleAddVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量添加成功'});
                        this.$emit('on-ok', true);
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;
                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量添加失败'});
                        }
                        console.error(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        // 批量修改
        async onClickMultipleOkUpdate(multipleSelection, refs) {
            if (multipleSelection.length === 0) {
                this.$message({showClose: true, type: 'error', message: '数据为空，批量修改失败'});
                return;
            }
            try {
                await formValidates.call(this, multipleSelection, refs);
                this.isMultipleLoading = true;
                putApisList(multipleSelection)
                    .then(res => {
                        this.multipleAddVisible = false;
                        this.$message({showClose: true, type: 'success', message: '批量修改成功'});
                        this.$emit('on-ok', true);
                    })
                    .catch(error => {
                        const data = error.response && error.response.data;
                        if (data && data.error) {
                            this.$message({showClose: true, type: 'error', message: data.error});
                        } else {
                            this.$message({showClose: true, type: 'error', message: '批量修改失败'});
                        }
                        console.error(error);
                    })
                    .finally(() => {
                        this.isMultipleLoading = false;
                    });
            } catch (error) {
                console.warn('表单的校验失败');
                this.$message({showClose: true, type: 'warn', message: '表单的校验失败'});
            }
        },
        onClickPrint() {
            dialogToPrint.call(this, this.$refs.dialog, [
                ...Array.from(document.querySelectorAll('.dialog-footer')),
                ...Array.from(document.querySelectorAll('.el-dialog__close'))
            ]);
        }
    }
};
</script>
